package com.tanhua.mongo.api;

import com.tanhua.api.service.VisitorsApi;
import com.tanhua.model.mongo.Visitors;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveVisitors(Visitors visitors) {
        //查看访问数据，一天只能保存一次
        Query query = new Query(
                Criteria.where("userId").is(visitors.getUserId())
                        .and("visitorUserId").is(visitors.getVisitorUserId())
                        .and("visitDate").is(visitors.getVisitDate())
        );

        // 不存在，保存
        if (!mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> findByUserId(Long userId,String date) {
        Criteria criteria = Criteria.where("userId").is(userId);

        if (StringUtils.isNotEmpty(date)) {
            criteria.and("date").gte(date);
        }

        return mongoTemplate.find(Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date"))), Visitors.class);
    }
}
